﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Windows.Controls
{
    using System.ComponentModel;
    using System.Reflection;
    using System.Windows.Controls.Primitives;
    public static class SelectorExtension
    {
        /// <summary>
        /// 将枚举类型作为Selector的数据源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="selector"></param>
        public static void SetEnumAsSource<T>(this Selector selector) where T : Enum
        {
            var dic = EnumAsDictionary<T>();
            selector.DisplayMemberPath = "Value";
            selector.SelectedValuePath = "Key";
            selector.ItemsSource = dic;
        }
        private static string GetDescription(FieldInfo field)
        {
            var att = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
            return att == null ? field.Name : ((DescriptionAttribute)att).Description;
        }

        /// <summary>
        /// 将枚举值和其描述作为字典返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private static Dictionary<T, string> EnumAsDictionary<T>() where T : Enum
        {
            var t = typeof(T);
            Dictionary<T, string> dic = new Dictionary<T, string>();
            var values = Enum.GetValues(t);
            foreach (T item in values)
            {
                var fieldName = Enum.GetName(t, item);
                var field = t.GetField(fieldName);
                dic.Add(item, GetDescription(field));
            }
            return dic;
        }
    }
}
